package com.stars.easyms.feign.request;

import feign.Request;
import feign.RequestTemplate;
import feign.codec.Encoder;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Type;
import java.util.Collection;

/**
 * 为feign增加request解析
 *
 * @author guoguifang
 * @date 2020-08-17 12:34
 * @since 1.6.1
 */
@Slf4j
public class EasyMsFeignEncoder extends BaseFeignRequestInterceptor implements Encoder {

    private Encoder encoder;

    private EasyMsGetFeignEncoder easyMsGetFeignEncoder;

    public EasyMsFeignEncoder(Encoder encoder) {
        this.encoder = encoder;
        this.easyMsGetFeignEncoder = new EasyMsGetFeignEncoder();
    }

    @Override
    public void encode(Object object, Type bodyType, RequestTemplate requestTemplate) {

        // 处理请求
        handleRequest(requestTemplate, object);

        Collection<String> contentTypes = requestTemplate.headers().get("Content-Type");

        // 判断是否是get模式，如果是get模式并且有requestBody参数的时候进行拼装
        if (object != null &&
                (Request.HttpMethod.GET.name().equals(requestTemplate.method())
                        || (contentTypes != null
                        && "application/x-www-form-urlencoded".equalsIgnoreCase(contentTypes.toArray(new String[0])[0])))) {
            easyMsGetFeignEncoder.encode(object, bodyType, requestTemplate);
        } else {
            encoder.encode(object, bodyType, requestTemplate);
        }
    }

}
